package com.kou.backend.handler;

import com.kou.backend.property.JwtProperties;
import com.kou.backend.resposne.ResultResponse;
import com.kou.backend.util.JsonUtils;
import com.kou.backend.util.JwtTokenUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 用户登出处理器
 *
 * @author: Chaojie.Kou
 * @since: 2023/9/1 10:45
 */
@Slf4j
@Component
public class LogoutHandler implements LogoutSuccessHandler {
    @Resource
    private JwtProperties jwtProperties;
    @Resource
    private JwtTokenUtils jwtTokenUtils;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, jakarta.servlet.ServletException {
        String token = request.getHeader(jwtProperties.getTokenHeader());
        if (StringUtils.isNotBlank(token)) {
            //用户登出,删除redis key
            jwtTokenUtils.clearToken(token);
            log.info("clear token :{}  logout success", token);
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().write(JsonUtils.toJSONString(ResultResponse.success("登出成功")));
        response.getWriter().flush();
    }
}
